//扇贝论坛

shanbay.forum = (function() {

  //回复/编辑
  //will be redirected after submitted successfully!
  this.reply_to = function(thread_url, thread_title, content, callback, post_to_url, post_data) {
    if (!post_to_url) {
      post_to_url = thread_url + "reply/";
    }
    if (!post_data) {
      post_data = {body: content};
    }
    post_data["csrfmiddlewaretoken"] = $.cookie("csrftoken");
    var fn_post = function() {
      shanbay.post(post_to_url, post_data, callback, "json");
    };

    //编辑时不需要发送短信
    if (post_to_url.indexOf("editpost") != -1) {
        return fn_post();
    }

    //发送回复提醒短信
    var msg_title = "[扇贝助手]新回复提醒";
    var msg_content = [
        "我在帖子 {",
        thread_title,
        "} 中提到了你：\n--------\n",
        content.slice(0, 200),
        "\n--------\n打开链接查看原文。链接：[ ",
        thread_url,
        " ]\n扇贝助手是什么？[ http://www.shanbay.com/forum/thread/85376/ ]",
    ].join("");

    var users = get_users_from_content(content);
    if (users.length == 0) {
      fn_post();
    } else {
      shanbay.mail.mail_to(users, msg_title, msg_content, fn_post);
    }
  };
  
  var get_users_from_content = function(content) {
    var users = content.match(/@[^ ,:　，：\n]+/g);
    if (!users) users = [];
    users = $.map(users, function(ele) {
      return ele.substring(1);
    })

    var urls = content.match(/\[.*\]\((.*)\)/g);
    if (!urls) urls = [];
    var users_from_url = shanbay.user.get_name_from_urls(urls).filter(function(user) {
        return !(!user);
    });

    return users.concat(users_from_url);
  };

  var replace_submit_button = function($form) {
    var $btn = $("<button>提交</button>").click(
        function() {
          $(this).after($("<span/>").text("正在提交..."));

          var thread_title = $("span.threadtitlecontent").text();
          var thread_url = window.location.href.replace(/(\?|#).*/, '');
          var content = $form.find("textarea:first").val();
          if (shanbay.user_info.id != 392608) content = content.replace(/\n+/g, "\n\n");
          var post_to_url = $form.prop("action");
          var post_data = {};
          $form.find("input[name], textarea[name]").each(function() {
            post_data[$(this).prop("name")] = $(this).val();
          });
          shanbay.forum.reply_to(thread_url, thread_title, content,
              function(result, data) {
                if (result == "success") {
                  window.location.href = data.redirect_url;
                  //若返回的链接与当前页一致将不会刷新，手动刷新
                  window.location.reload();
                }
              }, post_to_url, post_data);
          return false;
        });

    $form.find("input[type='submit']").hide().after($btn);
  };

  this.enhance_forum = function() {

    //论坛增强
    if ($("#djangoForumThreadPosts").size() > 0) {

      var $cur_form = $("div.newreply form").prop("id", "cur-form");
      //回复功能(@ta)
      $("div.post").each(
          function() {
            $sms_link = $(this).find("div.avatar a");
            var username = shanbay.user.get_name_from_urls([$sms_link.prop("href")])[0];

            $(this).find("a.reply").before(
                $("<a class='no-hover' href='#cur-form'/>").text("@Ta").click(
                    function() {
                      var ta = $cur_form.find("textarea")[0];
                      if (ta.value) {
                        ta.value += "\n";
                      }
                      ta.value += "@" + decodeURIComponent(username) + " ";

                      var last = ta.value.length;
                      ta.setSelectionRange(last, last);
                      ta.focus();
                    }).add($("<span>&nbsp;|&nbsp;</span>")));
          });

      //替换提交按钮
      replace_submit_button($("div.newreply form"));

      //替换回复回贴和编辑的提交按钮
      $("a.reply, a.edit").click(function() {
          var $this = $(this);
          var $form = null;
          shanbay.await(function() {
            $form = $this.parents("div.post:first").find("form:first");
            return $form.size() != 0;
          }, function() {
            $cur_form = $form.prop("id", "cur-form");
            replace_submit_button($form);
          }, 50);
      });
    }

  };

  return this;
})();

$("body").ready(function() {
  shanbay.forum.enhance_forum();
});
